var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var busboy = require('connect-busboy');
var session = require('express-session');

var config = require('./server/config/server.config');

var index = require('./routes/index');
var foods = require('./routes/food.route.js');
var headpic = require('./routes/headpic.route');
var idcardpic = require('./routes/idcardpic.route');
var foodpic = require('./routes/foodpic.route');
var login = require('./routes/login.route');
var foodtype = require('./routes/foodtype.route');
var merchants = require('./routes/merchant.route');
var register = require('./routes/register.route');
var order= require('./routes/order.route');
var notify = require('./routes/notify.route');

var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var ioservice = require('./server/service/socketio.service');

// app启动时连接数据库
mongoose.connect(config.mongodbUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'Mongodb connection error:'));
db.once('open', function () {
  console.log('Mongodb connected..');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client')));
app.use(busboy(
  {
    limits:
    {
      fileSize: 10 * 1024 * 1024
    }
  })
);
app.use("/headpic", express.static(config.headpicPath));
app.use("/idcardpic", express.static(config.idcardpicPath));
app.use("/foodpic", express.static(config.foodpicPath));
//初始化session
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));

// 允许跨域配置
app.all('/', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

//拦截
app.use('/manager.html', function (req, res, next) {
  console.log('[登录拦截]')
  if(!req.session.user){
    console.log('[已拦截]')
    var err = new Error('Not Login');
    err.status = 404;
    next(err);
  }
});

// 路由配置
app.use('/', index);
app.use('/foods', foods);
app.use('/merchant', merchants);
app.use('/foodtype', foodtype);
app.use('/orders', order);
app.use('/api/merchant/login', login);
app.use('/api/upload/foodpic', foodpic);
app.use('/api/upload/headpic', headpic);
app.use('/api/upload/idcardpic', idcardpic);
app.use('/api/merchant/register', register);
app.use('/api/notify', notify);
app.use('/hahahaha', function (req, res, next) {
  console.log('aaaaa');
  res.sendFile(__dirname+'/client/index.html');
})

http.listen(3001);
io.on('connection', function (socket) {
  console.log('a merchant socket connected..');
  socket.on('disconnect', function () {
    console.log('merchant socket disconnected..');
    console.log(this);
    ioservice.removeBySocket(this);
  });
  socket.on('id', function (data) {
    ioservice.addSocket(data.id, this);
    console.log('merchant socket added');
  });
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
